from django.shortcuts import render
from learning_logs.models import Topic, Entry
from learning_logs.forms import TopicForm, EntryForm
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib.auth.decorators import login_required


# Create your views here.
def index(request):
    return render(request, "learning_logs/index.html")


# @login_required(login_url='users:login')
@login_required
def topics(request):
    all_topic = Topic.objects.filter(owner=request.user).order_by('add_time')
    context = {"topics": all_topic}
    return render(request, "learning_logs/topics.html", context)


@login_required
def topic(request, topic_id):
    one_topic = Topic.objects.get(id=topic_id)
    if one_topic.owner != request.user:
        raise Http404
    entries = one_topic.entry_set.order_by("-add_time")
    context = {"topic": one_topic, "entries": entries}

    return render(request, "learning_logs/topic.html", context=context)


@login_required
def new_topic(req):
    if req.method != "POST":
        form = TopicForm()
    else:
        form = TopicForm(data=req.POST)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = req.user
            new_topic.save()
            return HttpResponseRedirect(reverse("ll:topics"))
    context = {"form": form}
    return render(req, "learning_logs/new_topic.html", context=context)


@login_required
def new_entry(req, topic_id):
    topic = Topic.objects.get(id=topic_id)
    if topic.owner != req.user:
        raise Http404
    if req.method != "POST":
        form = EntryForm()
    else:
        form = EntryForm(data=req.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()

            return HttpResponseRedirect(reverse("ll:topic", args=[topic_id]))

    context = {"topic": topic, "form": form}
    return render(req, "learning_logs/new_entry.html", context=context)


@login_required
def edit_entry(req, entry_id):
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    if topic.owner != req.user:
        raise Http404

    if req.method != "POST":
        form = EntryForm(instance=entry)
    else:
        form = EntryForm(instance=entry, data=req.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("ll:topic", args=[topic.id]))

    context = {"topic": topic, "form": form, "entry": entry}
    return render(req, "learning_logs/edit_entry.html", context=context)
